/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.theorcs.core.tapestry.model;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.libermundi.theorcs.core.CoreConstants;
import org.libermundi.theorcs.core.exceptions.EmailException;
import org.libermundi.theorcs.core.model.Email;
import org.libermundi.theorcs.core.tapestry.services.configuration.ApplicationConfig;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;

public abstract class AbstractEmail implements Email {
	private static final long serialVersionUID = -8946532895881189582L;
	
	protected final ApplicationConfig _appConfig;
	
	protected AbstractEmail(ApplicationConfig appConfig) {
		_appConfig = appConfig;
	}

	/*
	 * (non-Javadoc)
	 * @see org.libermundi.theorcs.core.model.Email#getDefaultMailMessage()
	 */
	@Override
	public SimpleMailMessage getDefaultMailMessage() throws EmailException {
		SimpleMailMessage mail = new SimpleMailMessage();
		mail.setFrom(_appConfig.getString(CoreConstants.EMAIL_DEFAULT_FROM));
		return mail;
	}

	/*
	 * (non-Javadoc)
	 * @see org.libermundi.theorcs.core.model.Email#getDefaultMimeMessageHelper(javax.mail.internet.MimeMessage)
	 */
	@Override
	public MimeMessageHelper getDefaultMimeMessageHelper(MimeMessage mimeMessage) throws EmailException {
		MimeMessageHelper message = new MimeMessageHelper(mimeMessage);

		try {
			message.setFrom(new InternetAddress(_appConfig.getString(CoreConstants.EMAIL_DEFAULT_FROM)));
		} catch (MessagingException e) {
			throw new EmailException(e.getMessage());
		}
		
		return message;
	}

	
	
}
